package cn.xiaoliu.hrm.cofig;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import javax.sql.DataSource;
import java.util.Arrays;

@Configuration
@EnableAuthorizationServer //开启授权服务配置
public class HrmAuthorTokenConfig extends AuthorizationServerConfigurerAdapter {
    /**
     * 授权服务安全配置：配置路径的放行（检查token的路径需要放行）
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                //对应/oauth/check_token ，路径公开
                .checkTokenAccess("permitAll()")
                //允许客户端进行表单身份验证,使用表单认证申请令牌
                .allowFormAuthenticationForClients();
    }

    /**
     * 客户端详情；配置客户端请求参数
     * @param clients
     * @throws Exception
     */
    @Autowired
    private DataSource dataSource;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        JdbcClientDetailsService clientDetailsService = getJdbcClientDetailsService();
        clients.withClientDetails(clientDetailsService);
    }

    private JdbcClientDetailsService getJdbcClientDetailsService() {
        JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        //加密解密
        clientDetailsService.setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }

    /**
     * 授权服务端点：配置授权码和令牌的管理以及存储方式
     * @param endpoints
     * @throws Exception
     */

    @Autowired
    private AuthenticationManager authenticationManager;
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                //1.密码授权模式需要
                .authenticationManager(authenticationManager)
                //2.授权码模式服务
                .authorizationCodeServices(authorCodeServices())
                //3.配置令牌管理服务
                .tokenServices(tokenStoreService())
                //允许post方式请求
                .allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET);

    }

    @Bean
    public AuthorizationServerTokenServices tokenStoreService() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        //获取客户端的详情
        defaultTokenServices.setClientDetailsService(getJdbcClientDetailsService());
        //支持刷新
        defaultTokenServices.setSupportRefreshToken(true);
        //token存储方式
        defaultTokenServices.setTokenStore(tokenStore());
        //设置token增强 - 设置token转换器
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter()));
        defaultTokenServices.setTokenEnhancer(tokenEnhancerChain);  //jwtAccessTokenConverter()
        return defaultTokenServices;
    }

    private final String key = "9966996";
    @Bean
    public TokenStore tokenStore() {
        //return new InMemoryTokenStore();
        JwtAccessTokenConverter tokenConverter = jwtAccessTokenConverter();
        JwtTokenStore tokenStore = new JwtTokenStore(tokenConverter);
        return tokenStore;
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        //使用jwtToken
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        tokenConverter.setSigningKey(key);
        return tokenConverter;
    }

    private AuthorizationCodeServices authorCodeServices() {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

}
